Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 | 'use client';
import { useState, useMemo } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Play, Plus, Trash2 } from 'lucide-react';
import { contentService } from '@/services';
import { ContentType } from '@/types';
import { toast } from 'sonner';
import { useTranslation } from 'react-i18next';
import i18n from '@/lib/i18n';
import { VideoUploadField } from '@/components/ui/video-upload-field';
// Manual series schema
// Manual series schema helper
const createManualSeriesSchema = (t: (key: string) => string) => z.object({
title: z.string().min(1, t('manualSeries.titleRequired')),
description: z.string().optional(),
year: z.number().min(1900).max(new Date().getFullYear() + 5).optional(),
poster_url: z.string().url(t('common.invalidData')).optional().or(z.literal('')),
backdrop_url: z.string().url(t('common.invalidData')).optional().or(z.literal('')),
active: z.boolean()
});
type ManualSeriesData = z.infer<ReturnType<typeof createManualSeriesSchema>>;
interface Season {
season_number: number;
title: string;
episodes: Episode[];
}
interface Episode {
episode_number: number;
title: string;
video_url: string;
}
interface ManualSeriesFormProps {
contentType: ContentType.SERIES | ContentType.ANIME;
open: boolean;
onOpenChange: (open: boolean) => void;
onClose: () => void;
}
export default function ManualSeriesForm({
contentType,
open,
onOpenChange,
onClose
}: ManualSeriesFormProps) {
const { t } = useTranslation();
// Create reactive schema based on current language
const manualSeriesSchema = useMemo(() => createManualSeriesSchema(t), [t]);
const [step, setStep] = useState<'basic' | 'seasons'>('basic');
const [seasons, setSeasons] = useState<Season[]>([
{
season_number: 1,
title: t('seriesManagement.defaultSeasonTitle', { number: 1 }),
episodes: [{ episode_number: 1, title: t('seriesManagement.defaultEpisodeTitle', { number: 1 }), video_url: '' }]
}
]);
const queryClient = useQueryClient();
const [pendingEpisodeFiles, setPendingEpisodeFiles] = useState<Record<string, File>>({});
const form = useForm<ManualSeriesData>({
resolver: zodResolver(manualSeriesSchema),
defaultValues: {
title: '',
description: '',
year: undefined,
poster_url: '',
backdrop_url: '',
active: true
}
});
// Create series mutation
const createSeriesMutation = useMutation({
mutationFn: async (data: ManualSeriesData & { seasons: Season[] }) => {
const result = await contentService.createSeries({
title: data.title,
description: data.description,
year: data.year,
poster_url: data.poster_url,
backdrop_url: data.backdrop_url,
active: data.active,
seasons: data.seasons.map(season => ({
season_number: season.season_number,
title: season.title,
episodes: season.episodes.filter(ep => ep.video_url.trim() !== '').map(episode => ({
episode_number: episode.episode_number,
title: episode.title,
video_url: episode.video_url
}))
})).filter(season => season.episodes.length > 0)
});
if (result.success) {
const newSeries = result.data;
// Handle pending video uploads for episodes
const uploadPromises = Object.entries(pendingEpisodeFiles).map(async ([key, file]) => {
try {
const [seasonIdx, episodeIdx] = key.split('-').map(Number);
const seasonData = data.seasons[seasonIdx];
const episodeData = seasonData.episodes[episodeIdx];
// Try to find the created episode. We match by season number and episode number.
// Note: This assumes newSeries contains the full nested structure.
// If backend doesn't return full tree, we'd need to fetch it or rely on other logic.
const createdSeason = newSeries.seasons?.find((s: any) => s.season_number === seasonData.season_number);
const createdEpisode = createdSeason?.episodes?.find((e: any) => e.episode_number === episodeData.episode_number);
if (createdEpisode?.id) {
await contentService.uploadEpisodeVideo(createdEpisode.id, file);
}
} catch (e) {
console.error('Failed to upload video for episode', key, e);
// We optimize to continue others even if one fails
}
});
if (uploadPromises.length > 0) {
toast.promise(Promise.all(uploadPromises), {
loading: t('createContent.uploadingEpisodes'),
success: t('createContent.uploadingEpisodesSuccess'),
error: t('createContent.uploadingEpisodesError')
});
await Promise.all(uploadPromises);
}
return result.data;
}
throw new Error(result.error.details);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['content', contentType] });
toast.success(t('createContent.createdSuccess', { type: getContentTypeLabel() }));
handleClose();
},
onError: (error: Error) => {
toast.error(t('notifications.content.createFailed', { message: error.message }));
}
});
const handleClose = () => {
onClose();
form.reset();
setStep('basic');
setSeasons([{
season_number: 1,
title: t('seriesManagement.defaultSeasonTitle', { number: 1 }),
episodes: [{ episode_number: 1, title: t('seriesManagement.defaultEpisodeTitle', { number: 1 }), video_url: '' }]
}]);
setPendingEpisodeFiles({});
createSeriesMutation.reset();
};
const handleBasicSubmit = () => {
setStep('seasons');
};
const handleFinalSubmit = () => {
const basicData = form.getValues();
createSeriesMutation.mutate({
...basicData,
seasons
});
};
const addSeason = () => {
const newSeasonNumber = seasons.length + 1;
setSeasons([...seasons, {
season_number: newSeasonNumber,
title: t('seriesManagement.defaultSeasonTitle', { number: newSeasonNumber }),
episodes: [{ episode_number: 1, title: t('seriesManagement.defaultEpisodeTitle', { number: 1 }), video_url: '' }]
}]);
};
const removeSeason = (seasonIndex: number) => {
if (seasons.length > 1) {
setSeasons(seasons.filter((_, index) => index !== seasonIndex));
}
};
const addEpisode = (seasonIndex: number) => {
const newSeasons = [...seasons];
const newEpisodeNumber = newSeasons[seasonIndex].episodes.length + 1;
newSeasons[seasonIndex].episodes.push({
episode_number: newEpisodeNumber,
title: t('seriesManagement.defaultEpisodeTitle', { number: newEpisodeNumber }),
video_url: ''
});
setSeasons(newSeasons);
};
const removeEpisode = (seasonIndex: number, episodeIndex: number) => {
const newSeasons = [...seasons];
if (newSeasons[seasonIndex].episodes.length > 1) {
newSeasons[seasonIndex].episodes.splice(episodeIndex, 1);
setSeasons(newSeasons);
}
};
const updateEpisode = (seasonIndex: number, episodeIndex: number, field: keyof Episode, value: string) => {
const newSeasons = [...seasons];
if (field === 'episode_number') {
newSeasons[seasonIndex].episodes[episodeIndex][field] = parseInt(value) || 1;
} else {
(newSeasons[seasonIndex].episodes[episodeIndex] as Record<keyof Episode, any>)[field] = value;
}
setSeasons(newSeasons);
};
const updateSeasonTitle = (seasonIndex: number, title: string) => {
const newSeasons = [...seasons];
newSeasons[seasonIndex].title = title;
setSeasons(newSeasons);
};
const getContentTypeLabel = () => {
return contentType === ContentType.SERIES ? t('contentTypeExtended.tvSeries') : t('contentTypeExtended.anime');
};
const getValidEpisodesCount = () => {
return seasons.reduce((total, season) => {
return total + season.episodes.filter(ep => ep.video_url.trim() !== '').length;
}, 0);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="!max-w-[65vw] !w-[65vw] max-h-[75vh] overflow-y-auto sm:!max-w-[65vw] md:!max-w-[65vw] lg:!max-w-[65vw]" style={{ width: '65vw', maxWidth: '65vw' }}>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Play className="h-5 w-5" />
{t('manualSeries.addManual', { type: getContentTypeLabel() })}
</DialogTitle>
<DialogDescription>
{t('manualSeries.dialogDescription', { type: getContentTypeLabel().toLowerCase() })}
</DialogDescription>
</DialogHeader>
<Tabs value={step} className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="basic">{t('manualSeries.stepBasicInfo')}</TabsTrigger>
<TabsTrigger value="seasons" disabled={step === 'basic'}>{t('manualSeries.stepSeasonsEpisodes')}</TabsTrigger>
</TabsList>
{/* Basic Info Tab */}
<TabsContent value="basic" className="space-y-6">
<form onSubmit={form.handleSubmit(handleBasicSubmit)} className="space-y-6">
<Card>
<CardHeader>
<CardTitle>{t('manualSeries.detailsTitle', { type: getContentTypeLabel() })}</CardTitle>
<CardDescription>
{t('manualSeries.detailsDescription', { type: getContentTypeLabel().toLowerCase() })}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{/* Title */}
<div>
<Label htmlFor="title">{t('manualSeries.titleRequired')}</Label>
<Input
id="title"
{...form.register('title')}
placeholder={t('manualSeries.titlePlaceholder', { type: getContentTypeLabel().toLowerCase() })}
/>
{form.formState.errors.title && (
<p className="text-sm text-red-600 mt-1">
{form.formState.errors.title.message}
</p>
)}
</div>
{/* Description */}
<div>
<Label htmlFor="description">{t('createContent.labels.description')}</Label>
<Textarea
id="description"
{...form.register('description')}
placeholder={t('manualSeries.descriptionPlaceholder', { type: getContentTypeLabel().toLowerCase() })}
rows={3}
/>
</div>
{/* Year */}
<div>
<Label htmlFor="year">{t('createContent.labels.year')}</Label>
<Input
id="year"
type="number"
{...form.register('year', { valueAsNumber: true })}
placeholder={t('createContent.form.yearPlaceholder')}
/>
</div>
{/* Poster URL */}
<div>
<Label htmlFor="poster_url">{t('createContent.labels.posterUrl')}</Label>
<Input
id="poster_url"
{...form.register('poster_url')}
placeholder={t('createContent.form.posterUrlPlaceholder')}
/>
</div>
{/* Backdrop URL */}
<div>
<Label htmlFor="backdrop_url">{t('createContent.labels.backdropUrl')}</Label>
<Input
id="backdrop_url"
{...form.register('backdrop_url')}
placeholder={t('createContent.form.backdropUrlPlaceholder')}
/>
</div>
{/* Active Status */}
<div className="flex items-center space-x-2">
<input
type="checkbox"
id="active"
{...form.register('active')}
className="rounded"
/>
<Label htmlFor="active">{t('manualSeries.activeType', { type: getContentTypeLabel() })}</Label>
</div>
</CardContent>
</Card>
<div className="flex justify-between">
<Button
type="button"
variant="outline"
onClick={handleClose}
>
{t('common.cancel')}
</Button>
<Button type="submit">
{t('manualSeries.nextAddSeasons')}
</Button>
</div>
</form>
</TabsContent>
{/* Seasons Tab */}
<TabsContent value="seasons" className="space-y-6">
<div className="space-y-4">
<div className="flex items-center justify-between">
<div>
<h3 className="text-lg font-medium">{t('seriesManagement.seasonsAndEpisodes')}</h3>
<p className="text-sm text-gray-600">
{t('manualSeries.validEpisodes', { count: getValidEpisodesCount() })}
</p>
</div>
<Button onClick={addSeason} variant="outline">
<Plus className="h-4 w-4 mr-2" />
{t('seriesManagement.addSeason')}
</Button>
</div>
{seasons.map((season, seasonIndex) => (
<Card key={seasonIndex}>
<CardHeader>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Input
value={season.title}
onChange={(e) => updateSeasonTitle(seasonIndex, e.target.value)}
className="font-medium"
/>
</div>
<div className="flex gap-2">
<Button
onClick={() => addEpisode(seasonIndex)}
variant="outline"
size="sm"
>
<Plus className="h-4 w-4 mr-1" />
{t('seriesManagement.episodes')}
</Button>
{seasons.length > 1 && (
<Button
onClick={() => removeSeason(seasonIndex)}
variant="outline"
size="sm"
>
<Trash2 className="h-4 w-4" />
</Button>
)}
</div>
</div>
</CardHeader>
<CardContent className="space-y-3">
{season.episodes.map((episode, episodeIndex) => (
<div key={episodeIndex} className="grid grid-cols-12 gap-2 items-center">
<div className="col-span-1">
<Label className="text-xs">{t('manualSeries.episodeShort', { number: episode.episode_number })}</Label>
</div>
<div className="col-span-4">
<Input
placeholder={t('seriesManagement.episodeTitlePlaceholder')}
value={episode.title}
onChange={(e) => updateEpisode(seasonIndex, episodeIndex, 'title', e.target.value)}
/>
</div>
<div className="col-span-6">
<VideoUploadField
value={episode.video_url}
onChange={(value) => updateEpisode(seasonIndex, episodeIndex, 'video_url', value)}
onUpload={async (file) => {
setPendingEpisodeFiles(prev => ({
...prev,
[`${seasonIndex}-${episodeIndex}`]: file
}));
return `[Pending Upload] ${file.name}`;
}}
disabled={createSeriesMutation.isPending}
placeholder={t('manualSeries.videoUrlOptionalPlaceholder')}
/>
</div>
<div className="col-span-1">
{season.episodes.length > 1 && (
<Button
onClick={() => removeEpisode(seasonIndex, episodeIndex)}
variant="outline"
size="sm"
>
<Trash2 className="h-4 w-4" />
</Button>
)}
</div>
</div>
))}
</CardContent>
</Card>
))}
</div>
<div className="flex justify-between">
<Button
type="button"
variant="outline"
onClick={() => setStep('basic')}
>
{t('common.back')}
</Button>
<div className="flex gap-2">
<Button
type="button"
variant="outline"
onClick={handleClose}
disabled={createSeriesMutation.isPending}
>
{t('common.cancel')}
</Button>
<Button
onClick={handleFinalSubmit}
disabled={createSeriesMutation.isPending || getValidEpisodesCount() === 0}
>
{createSeriesMutation.isPending ? t('createContent.creating') : t('manualSeries.createType', { type: getContentTypeLabel() })}
</Button>
</div>
</div>
</TabsContent>
</Tabs>
</DialogContent>
</Dialog>
);
}
|